package uk.co.hs.web.security.authentication;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.dao.DataAccessException;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;

/**
 * UtilisoftAuthenticationProviderSSO.
 */
public class UtilisoftAuthenticationProviderSSO extends AbstractUserDetailsAuthenticationProvider
{
  @Autowired(required=true)
  @Qualifier("hs_security.userService.sso")
  private UserDetailsService mUserDetailsService;

  /**
   * @see org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider
   * #retrieveUser(java.lang.String, org.springframework.security.authentication.UsernamePasswordAuthenticationToken)
   * {@inheritDoc}
   */
  protected UserDetails retrieveUser(String aUsername,
                                     UsernamePasswordAuthenticationToken aAuthentication) throws AuthenticationException
  {
    UserDetails loadedUser;
    try
    {
      loadedUser = mUserDetailsService.loadUserByUsername(aUsername);
    }
    catch (DataAccessException repositoryProblem)
    {
      throw new AuthenticationServiceException(repositoryProblem.getMessage(), repositoryProblem);
    }

    if (loadedUser == null)
    {
      throw new AuthenticationServiceException("User cannot be null");
    }
    return loadedUser;
  }

  /**
   * @see org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider
   * #additionalAuthenticationChecks(org.springframework.security.core.userdetails.UserDetails, org.springframework.security.authentication.UsernamePasswordAuthenticationToken)
   * {@inheritDoc}
   */
  protected void additionalAuthenticationChecks(UserDetails aUserDetails,
                                                UsernamePasswordAuthenticationToken aAuthentication) throws AuthenticationException
  { }
}
